import hashlib

from flask import Flask, request, json
from sqlalchemy import create_engine, Table, Select, or_, func, outerjoin
from sqlalchemy.orm import sessionmaker, declarative_base, scoped_session

app = Flask(__name__)

# 创建引擎，链接数据库
engine = create_engine('mysql+pymysql://root:admin@127.0.0.1:3306/mumu', echo=True)
# 打开数据库的连接会话
session = sessionmaker(engine)
# 保证线程安全
db_session = scoped_session(session)
# 获取基类
Base = declarative_base()


class User(Base):
    # 表结构反射加载
    __table__ = Table("user", Base.metadata, autoload_with=engine)

class Article(Base):
    # 表结构反射加载
    __table__ = Table("article", Base.metadata, autoload_with=engine)

class Favorite(Base):
    # 表结构反射加载
    __table__ = Table("favorite", Base.metadata, autoload_with=engine)

@app.route("/")
def my_article():
    username = request.args.get('username')
    all_articles = (db_session.query(User, Article, Favorite)
                        .outerjoin(Favorite, User.id == Favorite.user_id)
                        .outerjoin(Article, Favorite.article_id == Article.id)
                    ).filter(User.username == username).all()
    print(all_articles)
    for user, article, favorite in all_articles:
        print(user.username)
        print(article.content)
        print(favorite.article_id)
    return "ok"


if __name__ == '__main__':
    app.run(debug=True)